package com.kaibes.im.view.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;

import com.kaibes.im.R;
import com.kaibes.im.model.SocketWorker;

public class RegisterFragment extends KaibesFragment implements OnClickListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_register, container,
		false);
	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	super.onActivityCreated(savedInstanceState);
	getView().findViewById(R.id.btnRegisterComplete).setOnClickListener(
		this);
	getView().findViewById(R.id.btnRegisterCancel).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.btnRegisterComplete:
	    String username = ((EditText) getView().findViewById(
		    R.id.etRegisterUsername)).getText().toString().trim();
	    String password = ((EditText) getView().findViewById(
		    R.id.etRegisterPassword)).getText().toString().trim();
	    String question = ((EditText) getView().findViewById(
		    R.id.etRegisterQusetion_1)).getText().toString().trim();
	    String answer = ((EditText) getView().findViewById(
		    R.id.etRegisterAnswer_1)).getText().toString().trim();

	    if (username.equals("")) {
		getKaibesActivity().getAlertDialogData().reset()
			.setTitle(getString(R.string.registerError))
			.setMessage(getString(R.string.blankAccount));
		getKaibesActivity().showAlertDialog();
		break;
	    }
	    if (password.equals("")) {
		getKaibesActivity().getAlertDialogData().reset()
			.setTitle(getString(R.string.registerError))
			.setMessage(getString(R.string.blankPassword));
		getKaibesActivity().showAlertDialog();
		break;
	    }

	    LoginFragment fragment = ((LoginFragment) getKaibesActivity()
		    .findFragmentByTag(KaibesFragment.LOGIN_FRAGMENT));

	    fragment.setUsername(username);
	    fragment.setPassword(password);

	    getKaibesActivity().getKaibesApplication().sendData(1,
		    SocketWorker.ACTION_REGISTERED, username, password, question,
		    answer);
	    break;

	case R.id.btnRegisterCancel:
	    getKaibesActivity().onBackPressed();
	    break;

	default:
	    break;
	}
    }

    @Override
    public boolean onBackPressed() {
	getKaibesActivity().changeFragment(LoginFragment.class);
	return false;
    }

    @Override
    protected void reset() {
    }

}
